/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <mc/log.h>

#include "interface/network_port/link_info.h"

namespace dev {

bool NetworkPort_LinkInfo::update_link_status_by_pldm(uint8_t port_id) {
    uint8_t link_status = 0xFF;
    uint32_t speedMbps = 0xFFFFFFFF;
    bool ret = m_pldm_over_mctp_emulex->get_link_status(port_id, &link_status);
    if (!ret) {
        ilog("Error: Failed to update link status");
        LinkStatus.set_value(0xFF);
        SpeedMbps.set_value(0xFFFFFFFF);
        return false;
    }
    LinkStatus.set_value(link_status);
    ret = m_pldm_over_mctp_emulex->get_link_speed(port_id, &speedMbps);
    if (!ret) {
        ilog("Error: Failed to update link speed");
        SpeedMbps.set_value(0xFFFFFFFF);
        return false;
    }
    
    SpeedMbps.set_value(speedMbps);
    
    return true;
}

void NetworkPort_LinkInfo::start_pldm_update_task_emulex(pldm_over_mctp_emulex_ptr pldm_over_mctp,
                                                         mc::milliseconds      interval,
                                                         uint8_t               port_id) {
    m_pldm_over_mctp_emulex = pldm_over_mctp;
    m_pldm_timer            = new mc::core::timer(this);
    m_pldm_timer->timeout.connect([this, port_id]() {
        update_link_status_by_pldm(port_id);
    });
    m_pldm_timer->set_single_shot(false);
    m_pldm_timer->start(interval);
}

void NetworkPort_LinkInfo::stop_pldm_update_task() {
    if (m_pldm_timer) {
        m_pldm_timer->stop();
    }
    if (m_pldm_over_mctp_emulex) {
        m_pldm_over_mctp_emulex = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::NetworkPort_LinkInfo)